package com.cskaoyan.gateway.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IMemberService;
import com.mall.user.IUserLoginService;

import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.vo.UserLoginControllerBo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName MemberController
 * @Description 会员中心控制层
 * @Author ciggar
 * @Date 2019-08-07 14:26
 * @Version 1.0
 **/
@RestController
@RequestMapping("/user")
public class MemberController {

    @Reference(timeout = 3000,check = false)
    IMemberService memberService;
    @Reference(check = false)
    IUserLoginService userLoginService;

    @Reference(check = false)
    IKaptchaService kaptchaService;


    /**
     * 根据ID查询单条会员信息
     * @param id 编号
     * @return
     */
    @GetMapping("/member/{id}")
    public ResponseData searchMemberById(@PathVariable(name = "id")long id) {
        QueryMemberRequest request=new QueryMemberRequest();
        request.setUserId(id);
        QueryMemberResponse queryMemberResponse = memberService.queryMemberById(request);
        if (!queryMemberResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(queryMemberResponse.getMsg());
        }
        return new ResponseUtil<>().setData(queryMemberResponse);
    }

    /**
     * 会员信息更新
     * @return
     */
    @PutMapping("member")
    public ResponseData updateUser(@RequestBody UpdateMemberRequest request) {
        UpdateMemberResponse response = memberService.updateMember(request);
        if(response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    @GetMapping("login")
    public ResponseData checkLogin() {
        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userInfo = (String) servletRequest.getAttribute("userInfo");
        JSONObject jsonObject = JSON.parseObject(userInfo);
        String username = jsonObject.get("username").toString();
        CheckLoginRequest request = new CheckLoginRequest();
        request.setUsername(username);
        CheckLoginResponse response = userLoginService.checkLogin(request);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<CheckLoginResponse>().setData(response);
        }
        return new ResponseUtil().setErrorMsg("token已失效");
    }

    /**
     * 退出登录
     */
    @GetMapping("/loginOut")
    public ResponseData loginOut(HttpServletResponse response){
        Cookie cookie = new Cookie("access_token", null);
        cookie.setMaxAge(0);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        response.addCookie(cookie);
        return new ResponseUtil().setData(SysRetCodeConstants.SUCCESS.getMessage());
    }

    @PostMapping("login")
    @Anoymous
    public ResponseData userLogin(@RequestBody UserLoginControllerBo userBo, HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
        //判断验证码是否正确
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(userBo.getCaptcha());
        String kaptcha_uuid = CookieUtil.getCookieValue(servletRequest, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        Boolean kaptchaCodeIsRight = validateKaptchaCode(kaptchaCodeRequest, servletRequest);
        if (!kaptchaCodeIsRight) {
            return new ResponseUtil().setErrorMsg(Integer.parseInt(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getCode()),
                    SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());
        }
        UserLoginRequest request = new UserLoginRequest();
        String md5Password = DigestUtils.md5DigestAsHex(userBo.getUserPwd().getBytes());
        request.setPassword(md5Password);
        request.setUserName(userBo.getUserName());
        UserLoginResponse response = memberService.userLogin(request);
        if (SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode().equals(response.getCode())) {
            return new ResponseUtil().setErrorMsg(Integer.parseInt(response.getCode()), response.getMsg());
        }
        Cookie cookie = new Cookie("access_token", response.getToken());
        cookie.setDomain("localhost");
        cookie.setPath("/");
        servletResponse.addCookie(cookie);

        return new ResponseUtil().setData(response);
    }

    /**
     * 判断验证码是否正确
     *
     * @param servletRequest
     * @return
     */
    private Boolean validateKaptchaCode(KaptchaCodeRequest kaptchaCodeRequest, HttpServletRequest servletRequest) {

        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.validateKaptchaCode(kaptchaCodeRequest);
       /* if (kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS)) {
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(Integer.parseInt(SysRetCodeConstants.KAPTCHA_CODE_ERROR.getCode()),
                SysRetCodeConstants.KAPTCHA_CODE_ERROR.getMessage());*/
        if (kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return true;
        }
        return false;
    }
}

